package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import dao.ProductDao;
import dao.WishListDao;
import entity.Product;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/Product")
public class ProductService extends BasicServlet{

    //跳转到商品详情
    public String productDetails(HttpServletRequest request, HttpServletResponse response){
        String productId = request.getParameter("productId");
        System.out.println(productId);
        try {
            Product product = ProductDao.getProduct(productId);
            if(product == null || request.getSession(false) == null){
                response.sendRedirect("/"); return "Error";
            }
            request.getSession(false).setAttribute("review",ProductDao.getProductReview(productId));
            request.getSession(false).setAttribute("product",product);
            request.getRequestDispatcher("/page/productDetails.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }

    //添加收藏
    public Object productWish(HttpServletRequest request,HttpServletResponse response){
        String productId = request.getParameter("productId"),userId = request.getParameter("userId");
        String result = "";
        try {
            if(userId == null) {
                response.sendRedirect("/page/login"); return "Error";
            }
            result = WishListDao.addProductWish(productId,userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
    }

    //加入购物车
    public Object productCart(HttpServletRequest request,HttpServletResponse response){
        String productId = request.getParameter("productId"),userId = request.getParameter("userId");
        String result = "" , number = request.getParameter("number");
        try {
            if(userId == ""){
                response.sendRedirect("/page/login"); return "Error";
            }
           result = ProductDao.addCart(userId,productId,number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(result,SerializerFeature.WriteDateUseDateFormat);
    }
}
